package cn.sw.system.ai.manager;

import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ModelData;
import io.reactivex.Flowable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class AiManager {

    @Resource
    private ClientV4 clientV4;

    // 温度参数控制
    public static final float STABLE_TEMPERATURE = 0.05f; // 稳定输出
    private static final float UNSTABLE_TEMPERATURE = 0.99f; // 创造性输出

    /**
     * 流式请求（核心方法）
     */
    public Flowable<ModelData> doStreamRequest(List<ChatMessage> messages, Float temperature) {
        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4Flash)
                .stream(Boolean.TRUE)
                .temperature(temperature)
                .messages(messages)
                .build();
        
        try {
            return clientV4.invokeModelApi(request).getFlowable();
        } catch (Exception e) {
            e.printStackTrace();
            return Flowable.error(new RuntimeException("调用模型失败: " + e.getMessage()));
        }
    }
}
